package com.glo.spreadsheet2db.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class Spreadsheet implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8516408382155297833L;
	
	private long id;
	private Date savedDate;

	private SpreadsheetCell[][] cells;

	private int colCount;
	private int rowCount;

	public Spreadsheet(long id, Date savedDate, int rowCount, int colCount) {
		super();
		this.id = id;
		this.savedDate = new java.sql.Timestamp(savedDate.getTime());
		this.rowCount = rowCount;
		this.colCount = colCount;
	}
	
	public Spreadsheet(int rowCount, int colCount) {
		this(-1, new Date(), rowCount, colCount);
	}

	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}

	public Date getSavedDate() {
		return savedDate;
	}

	public List<SpreadsheetCell> getCellsList() {
		List<SpreadsheetCell> cellList = new ArrayList<SpreadsheetCell>();
		for (int r = 0; r < cells.length; r++) {
			SpreadsheetCell[] row = cells[r];
			for (int i = 0; i < row.length; i++) {
				if ( row[i] != null ) {
					cellList.add( row[i] );
				}
			}
		}
		return cellList;
	}

	public void attachCells(List<SpreadsheetCell> cells) {
		
		this.cells = new SpreadsheetCell[rowCount][colCount];
		
		for (SpreadsheetCell spreadsheetCell : cells) {
			
			int rowIndex = spreadsheetCell.getRowIndex();
			SpreadsheetCell[] row = this.cells[rowIndex];
			
			if( row == null ) {
				row = new SpreadsheetCell[colCount];
				this.cells[rowIndex] = row;
			}
			
			row[spreadsheetCell.getColumnIndex()] = spreadsheetCell;
			
			spreadsheetCell.setSheet(this);
		}
	}

	public int getColCount() {
		return colCount;
	}

	public void setColCount(int colCount) {
		this.colCount = colCount;
	}

	public int getRowCount() {
		return rowCount;
	}

	public void setRowCount(int rowCount) {
		this.rowCount = rowCount;
	}

	public SpreadsheetCell[][] getCells() {
		return cells;
	}
	
	public SpreadsheetCell[] getHeaderCells() {
		SpreadsheetCell[] header = new SpreadsheetCell[cells[0].length];
		for (int i = 0; i < cells[0].length; i++) {
			header[i] = cells[0][i];
		}
		return header;
	}
}
